package com.ch.roomdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.ch.roomdemo.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private var number = 0;
    private lateinit var myViewModel: PensionViewModel
    private lateinit var dataList: ArrayList<Pension>
    private lateinit var myAdapter: MyAdapter


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val activityMainBinding: ActivityMainBinding =
            DataBindingUtil.setContentView(this, R.layout.activity_main)
        myViewModel = ViewModelProviders.of(this).get(PensionViewModel::class.java)
        dataList = ArrayList()
        myAdapter = MyAdapter(dataList)
        activityMainBinding.recycleView.layoutManager = LinearLayoutManager(this)
        activityMainBinding.recycleView.adapter = myAdapter
        myViewModel.getAllPension().observe(this) {
            dataList.clear()
            dataList.addAll(it)
            myAdapter.notifyDataSetChanged()
        }
    }

    fun addPension(view: android.view.View) {
        number++
        val pension = Pension( number,"chenhu_$number", number + 5)
        myViewModel.insertPension(pension)
    }

    fun deletePension(view: android.view.View) {
        if (number < 1) {
            return
        }
        val pension = Pension(--number,"chenhu_$number", number + 5)
        myViewModel.deletePension(pension)
    }

    fun updatePension(view: android.view.View) {
        val pension = Pension(number,"这是改新后的名字_$number", number + 5)
        myViewModel.updatePension(pension)
    }

    fun queryPension(view: android.view.View) {
        myViewModel.getPensionById(3)
    }
}